import { createRouter, createWebHashHistory } from 'vue-router'
// 哈希路由及历史路由
import LayOut from '../views/LayOut/LayOut.vue'
import store from "../store/index.js"

// 路由配置
const routes = [
  //登录页面
  {
    path: "/login",
    name: "login",
    component: () => import("../views/pages/login.vue")
  },
  {
    path: "/",
    name: "layout",
    component: LayOut,
    //redirect: "/index",
    // 子路由/嵌套路由
    children: [
      {
        path: "/roles",
        name: "roles",
        component: () => import("../views/pages/rolesList.vue")
      },
      {
        path: "/user",
        name: "user",
        component: () => import("../views/pages/usersList.vue")
      },
      {
        path: "/goods",
        name: "goods",
        component: () => import("../views/pages/goodsList.vue")
      }
    ]
  },
  //注册页面
  {
    path: "/register",
    name: "register",
    component: () => import("../views/pages/register.vue")
  }
]
//生成hash路由对象
const router = createRouter({
  history: createWebHashHistory(),
  routes
})
router.beforeEach((to, from, next) => {
  // to 从哪个页面 from 到哪个页面 next 只有执行next()页面才会跳转
  // 判断用户是否登录
  console.log("store", store.state.uInfo)
  const UInfo = store.state.UInfo.userInfo
  if (!UInfo.username) {
    // 未登录，跳转到login页面
    if (to.path === "/register") {
      // 防止死循环
      next()
      return
    }
    if (to.path === "/login") {
      // 防止死循环
      next()
      return
    }
    next("/login")
  } else {
    next()
  }

})
// 暴露路由对象
export default router
